package com.example.amap.baidu.lifecycle

import android.content.Context
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.MapView
import com.example.amap.baidu.map.BaiDuMapView
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.map.IMapView
import com.example.amap.service.map.IMapService
import java.lang.ref.WeakReference

@Route(path = "/map/baidu/MapServiceImpl")
class MapServiceImpl : IMapService {
    companion object {
        private const val TAG = "baidu_LifecycleService"
    }

    private var mapViewContextWeakReference: WeakReference<Context>? = null
    private var mapViewWeakReference: WeakReference<MapView?>? = null

    override fun sdkInit(context: Context?) {
        context?.let {
            SDKInitializer.setAgreePrivacy(it, true)
            //在使用SDK各组件之前初始化context信息，传入ApplicationContext
            SDKInitializer.initialize(it)
            //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
            //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
            SDKInitializer.setCoordType(CoordType.BD09LL)
        }
    }

    override fun createMapView(context: Context): IMapView {
        super.createMapView(context)
        LogUtil.d(TAG, "createMapView context: $context")
        mapViewContextWeakReference = WeakReference(context)
        mapViewWeakReference = WeakReference(MapView(context))
        return BaiDuMapView(mapViewWeakReference?.get())
    }

    fun test() {
        mapViewWeakReference?.get()?.map?.apply {
            isMyLocationEnabled = true
//            setMyLocationData()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogUtil.d(TAG, "onCreate context: ${mapViewContextWeakReference?.get()} savedInstanceState: $savedInstanceState")
        mapViewWeakReference?.get()?.onCreate(mapViewContextWeakReference?.get(), savedInstanceState)
    }


    override fun onResume() {
        super.onResume()
        LogUtil.d(TAG, "onResume")
        mapViewWeakReference?.get()?.onResume()
    }

    override fun onPause() {
        super.onPause()
        LogUtil.d(TAG, "onPause")
        mapViewWeakReference?.get()?.onPause()
    }


    override fun onDestroy() {
        super.onDestroy()
        LogUtil.d(TAG, "onDestroy")
        mapViewWeakReference?.get()?.onDestroy()
    }
}